package com.xd.guessmusic.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xd.guessmusic.R;
import com.xd.guessmusic.data.Const;
import com.xd.guessmusic.model.IAlertDialogButtonListener;
import com.xd.guessmusic.model.IWordButtonClickListener;
import com.xd.guessmusic.model.Song;
import com.xd.guessmusic.model.WordButton;
import com.xd.guessmusic.myui.MyGridView;
import com.xd.guessmusic.util.MyLog;
import com.xd.guessmusic.util.MyPlayer;
import com.xd.guessmusic.util.Util;
import com.xd.guessmusic.weixin.WeixinUtil;

import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import static android.view.View.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.widget.LinearLayout.LayoutParams;
import static com.xd.guessmusic.util.Util.getRandomChar;

/**
 * Created by DGF on 2015/5/13.
 * 主界面
 */
public class MainActivity extends Activity implements IWordButtonClickListener {

    /**
     * 答案正确
     */
    private static final int STATUS_ANSWER_SUCCESS = 1;
    /**
     * 答案错误
     */
    private static final int STATUS_ANSWER_WRONG = 2;
    /**
     * 答案不完整
     */
    private static final int STATUS_ANSWER_LACK = 3;

    /**
     * 用于日志记录
     */
    private static final String TAG = "MainActivity";

    /**
     * 闪烁次数
     */
    private static final int SPARK_TIMES = 6;

    /**
     * 盘片旋转动画
     */
    private Animation discAnim;
    /**
     * 拨杆下拉动画
     */
    private Animation handlerPullAnim;
    /**
     * 拨杆恢复动画
     */
    private Animation handlerPushAnim;
    /**
     * 盘片
     */
    private ImageView imageDisc;
    /**
     * 拨杆
     */
    private ImageView imageHandler;
    /**
     * 播放按钮
     */
    private ImageButton btnPlay;
    /**
     * 待选文字网格列表
     */
    private MyGridView gridView;
    /**
     * 已选文字列表
     */
    private LinearLayout selectedLayout;
    /**
     * 当前歌曲
     */
    private Song currentSong = null;
    /**
     * 当前关卡索引
     */
    private int currentStateIndex = -1;
    /**
     * 已选择文字框
     */
    private ArrayList<WordButton> selectedBtns;
    /**
     * 待选文字框
     */
    private ArrayList<WordButton> wordButtons;

    /**
     * 当前金币数量
     */
    private int currentCoins = Const.TOTAL_COINS;

    /**
     * 当前金币显示的TextView
     */
    private TextView txtCurrentCoins;

    /**
     * 通关界面
     */
    private LinearLayout passLayout;

    /**
     * 是否正在播放音乐
     */
    private boolean isRunning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         * 读取游戏数据
         */
        int[] gameData = Util.loadData(this);
        currentStateIndex = gameData[Const.INDEX_LOAD_DATA_STAGE];
        currentCoins = gameData[Const.INDEX_LAOD_DATA_COINS];

        /**
         * 当前金币
         */
        txtCurrentCoins = (TextView)findViewById(R.id.txt_bar_coins);
        txtCurrentCoins.setText(currentCoins+"");

        /**
         * 初始化盘片动画，通过LinearInterpolator使用线性速度（匀速）
         */
        discAnim = AnimationUtils.loadAnimation(this, R.anim.rotate);
        LinearInterpolator discInterpolator = new LinearInterpolator();
        discAnim.setInterpolator(discInterpolator);
        discAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imageHandler.startAnimation(handlerPushAnim);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        /**
         * 初始化拨杆下拉的动画
         */
        handlerPullAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_45);
        LinearInterpolator handlerPullInterpolator = new LinearInterpolator();
        handlerPullAnim.setInterpolator(handlerPullInterpolator);
        handlerPullAnim.setFillAfter(true);//动画结束后保持当前状态
        handlerPullAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imageDisc.startAnimation(discAnim);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        /**
         * 初始化拨杆弹回的动画
         */
        handlerPushAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_d_45);
        LinearInterpolator handlerPushInterpolator = new LinearInterpolator();
        handlerPushAnim.setInterpolator(handlerPushInterpolator);
        handlerPushAnim.setFillAfter(true);
        handlerPushAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                btnPlay.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        /**
         * 开始播放
         * 1、拨杆旋转到盘片上
         * 2、盘片开始旋转
         * 3、盘片旋转完，拨杆返回
         */
        imageDisc = (ImageView)findViewById(R.id.image_pan_disc);
        imageHandler = (ImageView)findViewById(R.id.image_pan_handler);
        btnPlay = (ImageButton)findViewById(R.id.btn_play_start);
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handlerPlayButton();
            }
        });

        /**
         * 文字选择器
         */
        gridView = (MyGridView)this.findViewById(R.id.gridview_word);

        /**
         * 已选择文字的容器
         */
        selectedLayout = (LinearLayout)this.findViewById(R.id.word_select_container);

        initCurrentStageData();

        /**
         * 文字按钮点击事件
         */
        gridView.setOnWordButtonClick(this);

        /**
         * 处理删除按钮事件
         */
        handleDeleteWord();

        /**
         * 处理提示事件
         */
        handleTipAnswer();

        /**
         * 处理微信分享功能
         */
        handlerShareButton();
   }

    /**
     * 处理分享功能
     */
    private void handlerShareButton(){
        ImageButton btnShare = (ImageButton)findViewById(R.id.btn_share);
        if (btnShare != null){
            btnShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    WeixinUtil.getInstance(MainActivity.this).sendText("我正在玩疯狂猜歌游戏的第" + currentStateIndex + 1 + "关");
                }
            });
        }

        ImageButton btnPassShare = (ImageButton)findViewById(R.id.btn_pass_share);
        if (btnPassShare != null){
            btnPassShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bitmap bitmap = Util.getShot(MainActivity.this);
                    if (bitmap != null){
                        WeixinUtil.getInstance(MainActivity.this).sendBitmap(bitmap);
                    }
                }
            });
        }
    }

    /**
     * 播放音乐
     */
    private void handlerPlayButton(){
        if (!isRunning){
            isRunning = true;
        }

        //开始拨杆进入动画
        btnPlay.setVisibility(View.GONE);
        imageHandler.startAnimation(handlerPullAnim);

        //播放音乐
        MyPlayer.playSong(MainActivity.this, currentSong.getFileName());
    }

    /**
     * 当应用程序暂停时，清除动画
     */
    @Override
    protected void onPause() {
        /**
         * 保存游戏数据
         */
        Util.saveData(this, currentStateIndex - 1, currentCoins);

        /**
         * 清空游戏状态
         */
        imageDisc.clearAnimation();
        MyPlayer.stopSong(MainActivity.this);

        super.onPause();
    }

    /**
     * 获取指定关卡的音乐信息
     * @return
     */
    private Song loadStageSongInfo(int stageIndex){
        Song song = new Song();
        String[] songInfo = Const.SONG_INFO[stageIndex];
        song.setFileName(songInfo[Const.INDEX_FILE_NAME]);
        song.setName(songInfo[Const.INDEX_SONG_NAME]);
        return song;
    }

    /**
     * 初始化当前关卡的数据
     */
    private void initCurrentStageData(){

        /**
         * 获取当前关卡的歌曲信息
         */
        this.currentSong = loadStageSongInfo(++currentStateIndex);

        /**
         * 更新关卡
         */
        TextView txtCurrentStage = (TextView)findViewById(R.id.text_current_stage);
        if (txtCurrentStage != null){
            txtCurrentStage.setText(currentStateIndex+1+"");
        }

        /**
         * 初始化已选择框
         */
        selectedLayout.removeAllViews();
        int count = this.currentSong.getNameLength();
        selectedBtns = initSelectWords(count);
        for (int i=0;i< selectedBtns.size();i++){
            selectedLayout.addView(selectedBtns.get(i).getButton(), new LayoutParams(140,140));
        }

        /**
         * 初始化文字选择器
         */
        gridView.updateData(initWords());

        /**
         * 播放音乐
         */
        handlerPlayButton();
    }

    /**
     * 初始化已选择的文字框
     */
    private ArrayList<WordButton> initSelectWords(int count){
        ArrayList<WordButton> wordButtons = new ArrayList<>();
        for (int i=0;i<count; i++){
            View view = Util.getView(MainActivity.this, R.layout.self_ui_gridview_item);

            final WordButton wordButton = new WordButton("");
            wordButton.setButton((Button)view.findViewById(R.id.btn_item));
            wordButton.getButton().setText(wordButton.getText());
            wordButton.getButton().setTextColor(Color.WHITE);
            wordButton.getButton().setBackgroundResource(R.drawable.game_wordblank);
            wordButton.setVisible(false);

            /**
             * 点击已选按钮框，还原对应的待选文字框
             */
            wordButton.getButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clearAnswer(wordButton);
                }
            });

            wordButtons.add(wordButton);
        }
        return wordButtons;
    }

    /**
     * 初始化文字按钮
     */
    private ArrayList<WordButton> initWords(){
        /**
         * 生成随机汉字
         */
        String[] words = generateWords();

        /**
         * 打乱文字顺序
         * 从前面的文字中随机选择一个文字与当前文字进行交换
         */
        Random random = new Random();
        for (int i=words.length-1;i>0;i--){
            int index = random.nextInt(i);
            String randomStr = words[index];
            words[index]=words[i];
            words[i]=randomStr;
        }

        /**
         * 生成文字按钮
         */
        wordButtons = new ArrayList<>();
        for (int i=0;i< MyGridView.COUNT_WORDS; i++){
            wordButtons.add(new WordButton(words[i]));
        }
        return wordButtons;
    }

    /**
     * 生成随机文字数组
     * @return
     */
    private String[] generateWords(){
        String[] words = new String[MyGridView.COUNT_WORDS];

        /**
         * 添加歌曲名称
         */
        for (int i=0;i<currentSong.getNameLength();i++){
            words[i] = currentSong.getNameCharacters()[i]+"";
        }

        /**
         * 添加随机汉字
         */
        for (int i=currentSong.getNameLength();i<MyGridView.COUNT_WORDS;i++){
            words[i] = getRandomChar()+"";
        }

        return words;
    }

    /**
     * 点击文字按钮的事件
     * @param wordButton
     */
    @Override
    public void onWordButtonClick(WordButton wordButton) {
        //Toast.makeText(this, wordButton.getIndex()+"", Toast.LENGTH_SHORT).show();
        setSelectWord(wordButton);

        //检查答案
        int status = checkAnswer();
        if (status == STATUS_ANSWER_SUCCESS){
            //答案正确，获得相应的奖励，同时过关
            //Toast.makeText(this, "回答正确", Toast.LENGTH_SHORT).show();
            handlerPassEvent();
        }else if (status == STATUS_ANSWER_WRONG){
            //答案错误，闪烁文字提示错误
            sparkWords();
        }else if (status == STATUS_ANSWER_LACK){
            //答案缺失，恢复文字颜色为白色
            for (int i=0;i<selectedBtns.size();i++){
                selectedBtns.get(i).getButton().setTextColor(Color.WHITE);
            }
        }
    }

    /**
     * 清除答案
     * @param wordButton
     */
    private void clearAnswer(WordButton wordButton){
        if (wordButton.getText().length() < 1){
            return;
        }
        wordButton.getButton().setText("");
        wordButton.setText("");
        wordButton.setVisible(false);

        setButtonVisible(wordButtons.get(wordButton.getIndex()), View.VISIBLE);
    }

    /**
     * 设置选择的文字
     * @param wordButton
     */
    private void setSelectWord(WordButton wordButton){
        /**
         * 遍历已选文字框，找到没有文字的框填入
         */
        for (int i=0;i<this.selectedBtns.size();i++){
            if (this.selectedBtns.get(i).getText().length()<1){
                /**
                 * 设置答案文字框的文字和待选文字框的可见性
                 */
                this.selectedBtns.get(i).getButton().setText(wordButton.getText());
                this.selectedBtns.get(i).setText(wordButton.getText());
                this.selectedBtns.get(i).setVisible(true);
                /**
                 * 记录索引
                 */
                this.selectedBtns.get(i).setIndex(wordButton.getIndex());

                MyLog.d(TAG, wordButton.getIndex()+"");

                /**
                 * 设置待选框的可见性
                 */
                setButtonVisible(wordButton, View.GONE);

                break;
            }
        }
    }

    /**
     * 设置文字框可见性
     * @param button
     * @param visibility
     */
    private void setButtonVisible(WordButton button, int visibility){
        button.getButton().setVisibility(visibility);
        button.setVisible((visibility == View.VISIBLE) ? true : false);

        MyLog.i(TAG, "按钮索引："+button.getIndex()+"  文字："+button.getText()+ "  可见性："+button.isVisible());
    }

    /**
     * 检查答案
     * @return
     */
    private int checkAnswer(){
        for (int i=0;i<selectedBtns.size();i++){
            //如果待选框有空的，则答案不完整
            if (selectedBtns.get(i).getText().length()<1){
                return STATUS_ANSWER_LACK;
            }
        }

        //答案完整的话，检查正确性
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<selectedBtns.size();i++){
            sb.append(selectedBtns.get(i).getText());
        }

        return (sb.toString().equals(currentSong.getName()))? STATUS_ANSWER_SUCCESS : STATUS_ANSWER_WRONG;
    }

    /**
     * 闪烁答案
     */
    private void sparkWords(){
        //定时器相关
        TimerTask timerTask = new TimerTask() {
            /**
             * 是否切换颜色
             * change为true时，设置白色;
             * change为false时，设置红色;
             */
            boolean bChange = false;

            /**
             * 闪烁次数
             */
            int sparkTimes = 0;

            @Override
            public void run() {
                //android中对于界面的刷新必须在ui主线程中实现
                //Timer启动了另外一个线程，刷新ui时需要回到主线程中
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyLog.d(TAG, sparkTimes+"");

                        //闪烁次数
                        if (++sparkTimes > SPARK_TIMES){
                            return;
                        }
                        //执行闪烁：交替显示红色和白色文字
                        if (bChange){
                            for (int i=0;i<selectedBtns.size();i++){
                                selectedBtns.get(i).getButton().setTextColor(Color.RED);
                            }
                            bChange = false;
                        }else{
                            for (int i=0;i<selectedBtns.size();i++){
                                selectedBtns.get(i).getButton().setTextColor(Color.WHITE);
                            }
                            bChange = true;
                        }
                    }
                });
            }
        };

        Timer timer = new Timer();
        /**
         * task: 任务
         * delay: 开始时间
         * period: 持续时间
         */
        timer.schedule(timerTask, 0, 150);
    }

    /**
     * 处理过关事件
     */
    private void handlerPassEvent(){
        //显示过关界面
        passLayout = (LinearLayout)findViewById(R.id.layout_pass);
        passLayout.setVisibility(View.VISIBLE);

        //停止未完成的动画
        imageDisc.clearAnimation();

        //停止音乐
        MyPlayer.stopSong(MainActivity.this);

        //通关奖励金币
        handleCoins(getPassCoin());

        //当前关的索引
        TextView currentStagePassView = (TextView)passLayout.findViewById(R.id.text_current_stage_pass);
        if (currentStagePassView != null){
            currentStagePassView.setText(currentStateIndex + 1 + "");
        }

        //显示歌曲名称
        TextView currentSongName = (TextView)passLayout.findViewById(R.id.text_current_song_name_pass);
        if (currentSongName != null){
            currentSongName.setText(currentSong.getName());
        }

        //下一关按键处理
        ImageButton btnNext = (ImageButton)passLayout.findViewById(R.id.btn_next);
        if (btnNext != null){
            btnNext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (judgeAppPassed()){
                        //进入通关界面
                        Util.startActivity(MainActivity.this, AppPassView.class);
                    }else{
                        //进入新一关
                        passLayout.setVisibility(View.GONE);

                        //加载关卡数据
                        initCurrentStageData();
                    }
                }
            });
        }

        //分享到微信
        ImageButton btnShare = (ImageButton)passLayout.findViewById(R.id.btn_share);
        if (btnShare != null){
            btnShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
    }

    /**
     * 通关的金币
     */
    private int getPassCoin(){
        return 10;
    }

    /**
     * 判断是否通关
     * @return
     */
    private boolean judgeAppPassed(){
        return (currentStateIndex + 1) == Const.SONG_INFO.length;
    }

    /**
     * 删除文字
     */
    private void deleteOneWord(){
        //减少金币
        if (!handleCoins(-getDeleteWordCoins())){
            //金币不够，显示提示对话框
            return;
        }

        //将这个索引对应的WordButton设置为不可见
        //随机删除非答案的一个文字
        setButtonVisible(findNotAnswerWord(), View.INVISIBLE);
    }

    /**
     * 增加或者减少指定数目的金币
     * @param data
     * @return true 增加/减少成功, false 失败
     */
    private boolean handleCoins(int data){
        //判断当前总得金币数量是否可被减少
        if (currentCoins + data < 0){
            Util.showDialog(MainActivity.this,
                    "金币不足，去商店补充？",
                    new IAlertDialogButtonListener() {
                        @Override
                        public void onClick() {
                            Toast.makeText(MainActivity.this, "商店还没开放哦！", Toast.LENGTH_SHORT).show();
                        }
                    });
            return false;
        }
        currentCoins += data;
        txtCurrentCoins.setText(currentCoins+"");

        MyPlayer.playSound(MainActivity.this, MyPlayer.INDEX_SOUND_COIN);
        return true;
    }

    /**
     * 找到一个不是答案的文字，并且当前是可见的
     * @return
     */
    private WordButton findNotAnswerWord(){
        Random random = new Random();
        WordButton buf = null;

        while(true){
            int index = random.nextInt(MyGridView.COUNT_WORDS);
            buf = wordButtons.get(index);

            if (buf.isVisible() && !isTheAnswerWord(buf)){
                return buf;
            }
        }
    }

    /**
     * 判断某个文字是否为答案
     * @param word
     * @return
     */
    private boolean isTheAnswerWord(WordButton word){
        boolean result = false;

        for (int i=0;i<currentSong.getNameLength();i++){
            if (word.getText().equals(
                    (""+currentSong.getNameCharacters()[i]))){
                result = true;
                break;
            }
        }

        return result;
    }

    /**
     * 从配置文件中读取删除操作所要用的金币
     * @return
     */
    private int getDeleteWordCoins(){
        return getResources().getInteger(R.integer.pay_delete_word);
    }

    /**
     * 从配置文件中读取提示需要花费的近金币数
     * @return
     */
    private int getTipCoins(){
        return getResources().getInteger(R.integer.pay_tip_answer);
    }

    /**
     * 处理删除待选文字事件
     */
    private void handleDeleteWord(){
        ImageButton btnDelete = (ImageButton)findViewById(R.id.btn_delete_word);
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Util.showDialog(MainActivity.this,
                        "确认花掉"+getDeleteWordCoins()+"个金币去掉一个错误答案？",
                        new IAlertDialogButtonListener() {
                            @Override
                            public void onClick() {
                                deleteOneWord();
                            }
                        });
            }
        });
    }

    /**
     * 自动选择一个答案
     */
    private void tipAnswer(){
        //减少金币数量
        if (!handleCoins(-getTipCoins())){
            //金币数量不足，显示对话框
            return;
        }

        boolean tipWord = false;
        for (int i=0;i<selectedBtns.size();i++){
            if (selectedBtns.get(i).getText().length() == 0){
                //根据当前的答案框的条件选择对应的文字并填入
                onWordButtonClick(findAnswerWord(i));

                tipWord = true;
                break;
            }
        }

        //没有找到可以填充的答案
        if (!tipWord){
            //闪烁文字提示用户
            sparkWords();
            //加回金币
            handleCoins(getTipCoins());
        }
    }

    /**
     * 找到一个答案文字
     * @param index 当前需要添入答案框的索引
     * @return
     */
    private WordButton findAnswerWord(int index){
        WordButton buf = null;

        for (int i=0;i<MyGridView.COUNT_WORDS;i++){
            buf = wordButtons.get(i);
            if (buf.getText().equals(""+currentSong.getNameCharacters()[index])){
                return buf;
            }
        }

        return buf;
    }

    /**
     * 处理答案提示事件
     */
    private void handleTipAnswer(){
        ImageButton btnTip = (ImageButton)findViewById(R.id.btn_tip_answer);
        btnTip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Util.showDialog(MainActivity.this,
                        "确认花掉"+getTipCoins()+"个金币获得一个文字提示？",
                        new IAlertDialogButtonListener() {
                            @Override
                            public void onClick() {
                                tipAnswer();
                            }
                        });
            }
        });
    }
}
